from google.appengine.ext import db
from google.appengine.api import users
import datetime

# def get_gae_user():
#     return users.get_current_user()

# def gae_user_to_user(gae_user):
#     return db.get(db.Key.from_path('User', gae_user.user_id()))
#     # return User.all().filter("user_id=", gae_user.user_id()).get()

class User(db.Model):
    """User"""
    profile_image = db.Blob()
    user = db.UserProperty()
    name = db.StringProperty()
    description = db.TextProperty()
    creation_time = db.DateTimeProperty(auto_now_add=True)
    admin = db.BooleanProperty(default=False)
    deactivated = db.BooleanProperty(default=False)

    # __eq__, __ne__ is from http://stackoverflow.com/a/3074404
    def __eq__(self, other):
        if isinstance(other, User):
            return self.user == other.user
        return NotImplemented

    def __ne__(self, other):
        result = self.__eq__(other)
        if result is NotImplemented:
            return result
        return not result

    @classmethod
    def get_current_user(cls):
        return cls.all().filter("user =", users.get_current_user()).get()

    @classmethod
    def create(cls, email=None):
        """ returns an User instance. It's your work to put the instance into DB. """
        # This should be implemented as override __init__ method?
        if email is None:
            user = users.User()
        else:
            user = users.User(email)
        return User(user=user)
        

class Item(db.Model):
    title = db.StringProperty()
    description = db.TextProperty()
    price = db.IntegerProperty()
    creation_time = db.DateTimeProperty(auto_now_add=True)
    expiration_date = db.DateProperty(default=datetime.date.today() + datetime.timedelta(days=7))
    seller = db.ReferenceProperty(User)

    @classmethod
    def alive_all(cls):
        """ returns items which are not expired """
        return cls.all().filter("expiration_date >", datetime.date.today()).order("expiration_date")

    @classmethod
    def expired_all(cls):
        """ returns items which are expired """
        return cls.all().filter("expiration_date <=", datetime.date.today()).order("expiration_date")

    def is_expired(self):
        return self.expiration_date <= datetime.date.today()

    # def is_sold_by(self, user):
    #     return self.seller == user

def initialize_storage(clear=False):
    if clear:
        db.delete(db.Query(keys_only=True)) # delete all
        # http://stackoverflow.com/questions/1062540/how-to-delete-all-datastore-in-google-app-engine/10856555#10856555

    user_names = "Alpaca Bison Cat Dog Elephant Fox Gnu Horse Iguana "\
            "Jaguar Koala Lion Moose Nightingale Ox Parrot Quail "\
            "Rabbit Sheep Tiger Urial Vulture Wallaby Xml Yak Zebra".split(" ")
    item_names = "Red apple,Green ball,Blue carrot,Red desk,Green easel,"\
            "Blue file,Red glove,Green house,Blue ink,Blue rose".split(",")

    user_entities = []
    for n in user_names:
        uU = users.User(n + "@example.com")
        user = User(name=n, user=uU)
        user_entities.append(user)
    db.put(user_entities)

    item_entities = []
    for user in user_entities:
        for price, name in enumerate(item_names):
            item = Item(title=name, seller=user, parent=user, price=price+1)
            if name == "Blue rose":
                item.expiration_date = datetime.date.today() - datetime.timedelta(days=10)
            item_entities.append(item)
    db.put(item_entities)

    admins = [["hardcodetest1@gmail.com", "admin_test1"],
              ["hardcodetest2@gmail.com", "admin_test2"],
              ["yellowcruet@gmail.com", "yellowcruet_admin"]]
    for email, name in admins:
        user = User.create(email)
        user.name = name
        user.admin = True
        user.put()
        # uU = users.User(email)
        # user = User(name=name, user=uU, admin=True)
        # user.put()

